<?php

namespace App\Http\Middleware;

use App\User;
use Closure;
use App\Http\Service\UserInstance;

class AuthMiddleware
{   //Bearer空格
    public function handle($request, Closure $next)
    {
        // 执行动作
        $authorization = $request->header('authorization');
        $api_token     = substr($authorization, 7);

        if (!$api_token) {
            return response()->json(['code' => 1, 'msg' => "api_token不能为空", 'data' => []]);
        }
        $user = User::where(['api_token' => $api_token,'deleted_at'=>null])->first();

        if (!$user) {
            return response()->json(['code' => 1, 'msg' => "api_token错误", 'data' => []]);
        }

        UserInstance::getInstance()->set($user);

        return $next($request);
    }
}
